<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="CRC校验 CRC算法 CRC实现">
    <meta name="description" content="本篇文章通俗的讲解了何谓CRC？如何生成CRC码以及如何使用CRC码校验，最后采用多种思路用C语言实现CRC校验。



背景最近在研究温湿度传感器SHT30，该传感器使用IIC接口进行通信，在读取数据时，该传感器分别在发送 16bit 的">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>如何通俗的理解CRC校验并用C语言实现 | Mculover666</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.1"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Mculover666</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-list" style="zoom: 0.6;"></i>
      
      <span>系列教程</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/posts/578764034/">
          
          <span>STM32CubeMX</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="https://blog.csdn.net/Mculover666" target="_blank" rel="noopener" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>CSDN</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/download" class="waves-effect waves-light">
      
      <i class="fas fa-download" style="zoom: 0.6;"></i>
      
      <span>资源下载</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Mculover666</div>
        <div class="logo-desc">
            
            嵌入式 STM32 物联网领域的教程及精彩内容分享
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-list"></i>
			
			系列教程
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>   
				
                  <a href="/posts/578764034/ " style="margin-left:75px";>
				  
		          <span>STM32CubeMX</span>
                  </a>
                </li>
               
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="https://blog.csdn.net/Mculover666" target="_blank" rel="noopener" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			CSDN
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/download" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-download"></i>
			
			资源下载
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/Mculover666" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/Mculover666" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/16.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">如何通俗的理解CRC校验并用C语言实现</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/CRC%E6%A0%A1%E9%AA%8C%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">CRC校验算法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                算法
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-08-06
                </div>
                

                

                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>本篇文章通俗的讲解了何谓CRC？如何生成CRC码以及如何使用CRC码校验，最后采用<strong>多种思路</strong>用C语言实现CRC校验。</p>
<p><img src="http://mculover666.cn/image/20190829/a5uVezmqAgdw.png?imageslim" alt="mark"></p>
<a id="more"></a>

<h1 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h1><p>最近在研究温湿度传感器SHT30，该传感器使用IIC接口进行通信，在读取数据时，该传感器<strong>分别</strong>在发送 <code>16bit</code> 的温度和湿度数据后，发送了 <code>8bit</code> 的CRC校验数据，如图所示：</p>
<p><img src="http://mculover666.cn/image/20190808/OiN41VkYPDat.png?imageslim" alt="mark"></p>
<p>那么，问题来了：</p>
<ul>
<li><strong>CRC是个什么东东？</strong></li>
<li><strong>如何计算得到CRC码？</strong></li>
<li><strong>如何使用CRC码校验？</strong></li>
<li><strong>如何用C语言实现该CRC校验？</strong></li>
</ul>
<h1 id="CRC到底是个什么东东"><a href="#CRC到底是个什么东东" class="headerlink" title="CRC到底是个什么东东"></a>CRC到底是个什么东东</h1><p>CRC学名叫做<strong>循环冗余校验</strong>，全称 <code>cyclic redundancy check</code>，这个词有两个含义：</p>
<ul>
<li>循环冗余校验<strong>功能</strong>：对要传送的数据进行多项式计算，并将所得结果跟着传送数据后发送，接收端再次进行校验；</li>
<li>循环冗余校验<strong>码</strong>：对要传送的数据进行多项式计算后得到的值称为循环冗余校验码。</li>
</ul>
<p>等等，好像跑题了，这个是官方解释，那么，我们该如何通俗的理解呢？接下里我带领大家在实战中领悟CRC的奥秘~</p>
<h1 id="计算CRC码之前的准备工作"><a href="#计算CRC码之前的准备工作" class="headerlink" title="计算CRC码之前的准备工作"></a>计算CRC码之前的准备工作</h1><h2 id="关键点1-——-模2除法"><a href="#关键点1-——-模2除法" class="headerlink" title="关键点1 —— 模2除法"></a>关键点1 —— 模2除法</h2><p>在CRC校验规则中，原始数据与给定的除数之间进行<strong>模2除法</strong>得到CRC码，发送端将原始数据和CRC码一起传送到接收端，接收端再</p>
<p>那么，模2除法的规则是怎样的呢？它和普通除法有什么不一样的呢？</p>
<p>模2除法与普通的算术除法类似，但是它有两个区别：</p>
<ul>
<li>不向上借位；</li>
<li>不比较除数和被除数的相同位数值的大小，只要以相同位数进行相除即可；</li>
</ul>
<p>所以在模2除法中二进制运算结果如下：</p>
<ul>
<li>1 - 1 = 0</li>
<li>1 - 0 = 1</li>
<li>0 - 1 = 1</li>
<li>0 - 0 = 1</li>
</ul>
<p>乍一看，这个运算规则是不是似曾相识~这就是我们熟悉的<strong>异或运算</strong>，可以总结出“模2除法”的规则：</p>
<pre><code>模2除法不借位，相同位置用异或。</code></pre><p>”最后用一个例子演示一下“模2除法”：</p>
<p><img src="http://mculover666.cn/image/20190808/cvO25i2jnBFf.png?imageslim" alt="mark"></p>
<h2 id="关键点2-——-确定“生成多项式”"><a href="#关键点2-——-确定“生成多项式”" class="headerlink" title="关键点2 —— 确定“生成多项式”"></a>关键点2 —— 确定“生成多项式”</h2><p>生成多项式既确定了如何改造原始数据作为被除数，也确定了除数，还确定了CRC码的位数，是整个CRC码生成过程的关键。</p>
<p>标准的CRC生成多项式如下表：</p>
<table>
<thead>
<tr>
<th align="center">名称</th>
<th align="center">生成多项式</th>
<th align="center">简记式</th>
</tr>
</thead>
<tbody><tr>
<td align="center">CRC-4</td>
<td align="center">x4+x+1</td>
<td align="center">3</td>
</tr>
<tr>
<td align="center">CRC-8</td>
<td align="center">x8+x5+x4+1</td>
<td align="center">0x31</td>
</tr>
<tr>
<td align="center">CRC-8</td>
<td align="center">x8+x2+x1+1</td>
<td align="center">0x07</td>
</tr>
<tr>
<td align="center">CRC-8</td>
<td align="center">x8+x6+x4+x3+x2+x1</td>
<td align="center">0x5E</td>
</tr>
<tr>
<td align="center">CRC-12</td>
<td align="center">x12+x11+x3+x+1</td>
<td align="center">0x80F</td>
</tr>
<tr>
<td align="center">CRC-16</td>
<td align="center">x16+x15+x2+1</td>
<td align="center">0x8005</td>
</tr>
<tr>
<td align="center">CRC16-CCITT</td>
<td align="center">x16+x12+x5+1</td>
<td align="center">0x1021</td>
</tr>
<tr>
<td align="center">CRC-32</td>
<td align="center">x32+x26+x23+…+x2+x+1</td>
<td align="center">0x04C11DB7</td>
</tr>
<tr>
<td align="center">CRC-32c</td>
<td align="center">x32+x28+x27+…+x8+x6+1</td>
<td align="center">0x1EDC6F41</td>
</tr>
</tbody></table>
<h1 id="（发送方）如何计算CRC码"><a href="#（发送方）如何计算CRC码" class="headerlink" title="（发送方）如何计算CRC码"></a>（发送方）如何计算CRC码</h1><p>假设选择的CRC生成多项式为：<br>$$<br>G(X) = X^4 + X^3 + 1<br>$$<br>要求：请写出二进制序列10110011的CRC校验码。</p>
<p>计算过程如下：</p>
<h2 id="1-将生成多项式转换成二进制数"><a href="#1-将生成多项式转换成二进制数" class="headerlink" title="1.将生成多项式转换成二进制数"></a>1.将生成多项式转换成二进制数</h2><ul>
<li>二进制数的总位数 = 最高位的幂次 + 1</li>
<li>多项式中只列出二进制值为1的位</li>
</ul>
<p>根据这个规则可以得到，该生成多项式$G(X)$对应的二进制数总共有 5 位（4+1），其中第 4 位、第 3 位、第 0 位的二进制值为1，其它位均为0，所以该生成多项式的二进制为： <code>11001</code>。</p>
<h2 id="2-根据生成多项式确定除数"><a href="#2-根据生成多项式确定除数" class="headerlink" title="2.根据生成多项式确定除数"></a>2.根据生成多项式确定除数</h2><p>除数就是生成多项式的二进制数，所以除数为：<code>11001</code>。</p>
<h2 id="3-根据生成多项式确定被除数和CRC码的位数"><a href="#3-根据生成多项式确定被除数和CRC码的位数" class="headerlink" title="3.根据生成多项式确定被除数和CRC码的位数"></a>3.根据生成多项式确定被除数和CRC码的位数</h2><ul>
<li>CRC码的位数 = 生成多项式的二进制位数 - 1</li>
</ul>
<p>根据之前转换的生成多项式的二进制位数，CRC码的位数为：<code>5 - 1 = 4</code>位。</p>
<p>在原始数据后加上 <code>CRC码的位数</code> 个0，作为被除数，即：<code>101100110000</code>。</p>
<h2 id="4-使用模2除法计算CRC码"><a href="#4-使用模2除法计算CRC码" class="headerlink" title="4.使用模2除法计算CRC码"></a>4.使用模2除法计算CRC码</h2><p>除数确定了，被除数也确定了，CRC码的位数也确定了，万事具备，只欠东风，接下来请出我们的“模2除法”，开始计算CRC码：</p>
<p><img src="http://mculover666.cn/image/20190808/r9MOz2k23mjY.png?imageslim" alt="mark"></p>
<p>由图上的计算过程可知，得到的CRC码为： <code>0100</code>。</p>
<h1 id="接收方-如何使用CRC码校验数据"><a href="#接收方-如何使用CRC码校验数据" class="headerlink" title="(接收方)如何使用CRC码校验数据"></a>(接收方)如何使用CRC码校验数据</h1><p>接收方接收到原始数据<code>10110011</code>和CRC校验码<code>0100</code>后，校验数据是否正确的方法如下：</p>
<h2 id="1-获取发送方所使用的生成多项式"><a href="#1-获取发送方所使用的生成多项式" class="headerlink" title="1.获取发送方所使用的生成多项式"></a>1.获取发送方所使用的生成多项式</h2><p>接收方首先要获取发送方所使用的生成多项式，然后<strong>使用该生成多项式的二进制数确定除数</strong>，即：<code>11001</code>。</p>
<h2 id="2-根据接收到的数据和CRC码确定被除数"><a href="#2-根据接收到的数据和CRC码确定被除数" class="headerlink" title="2.根据接收到的数据和CRC码确定被除数"></a>2.根据接收到的数据和CRC码确定被除数</h2><p>将接收到的数据和CRC码拼接起来，作为被除数，这里为：<code>101100110100</code>。</p>
<h2 id="3-使用模2除法校验数据正确性"><a href="#3-使用模2除法校验数据正确性" class="headerlink" title="3.使用模2除法校验数据正确性"></a>3.使用模2除法校验数据正确性</h2><p>除数确定了，被除数也确定了，接下来再次使用“模2除法”校验：</p>
<p><img src="http://mculover666.cn/image/20190808/S3BJImRSXHbz.png?imageslim" alt="mark"></p>
<p>由图上的计算过程可知，校验得到的余数为<code>0</code>，接收结果：正确！</p>
<p><strong>一旦接收数据和接收的CRC码中有一位改变，则计算结果余数不为0，校验失败。</strong></p>
<h1 id="使用C语言实现CRC校验"><a href="#使用C语言实现CRC校验" class="headerlink" title="使用C语言实现CRC校验"></a>使用C语言实现CRC校验</h1><h2 id="算法1-——-按位校验思想"><a href="#算法1-——-按位校验思想" class="headerlink" title="算法1 —— 按位校验思想"></a>算法1 —— 按位校验思想</h2><h3 id="CRC4"><a href="#CRC4" class="headerlink" title="CRC4"></a>CRC4</h3><p>对于简单的CRC-4，实现代码如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdint.h></span></span>

<span class="token macro property">#<span class="token directive keyword">define</span> CRC4_POLYNOMIAL 0xC8   </span><span class="token comment" spellcheck="true">/* 11011后面补0凑8位数：11011000*/</span>

uint8_t <span class="token function">CheckCrc4</span><span class="token punctuation">(</span>uint8_t <span class="token keyword">const</span> message<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    uint8_t  remainder<span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">//余数</span>
    uint8_t  i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>         <span class="token comment" spellcheck="true">//循环变量</span>

    <span class="token comment" spellcheck="true">/* 初始化，余数=原始数据 */</span>
    remainder <span class="token operator">=</span> message<span class="token punctuation">;</span>

    <span class="token comment" spellcheck="true">/* 从最高位开始依次计算  */</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">8</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>remainder <span class="token operator">&amp;</span> <span class="token number">0x80</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            remainder <span class="token operator">^</span><span class="token operator">=</span> POLYNOMIAL<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        remainder <span class="token operator">=</span> <span class="token punctuation">(</span>remainder <span class="token operator">&lt;&lt;</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 返回计算的CRC码 */</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span>remainder <span class="token operator">>></span> <span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>测试代码如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    uint8_t dat <span class="token operator">=</span> <span class="token number">0xB3</span><span class="token punctuation">;</span>
    uint8_t crc <span class="token operator">=</span> <span class="token function">CheckCrc4</span><span class="token punctuation">(</span>dat<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"crc = %#x\n"</span><span class="token punctuation">,</span> crc<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>crc <span class="token operator">==</span> <span class="token number">0x4</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"ok.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">else</span>
    <span class="token punctuation">{</span>
      <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"fail.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>运行结果如下：</p>
<p><img src="http://mculover666.cn/image/20190809/LcGji03UtDJ9.png?imageslim" alt="mark"></p>
<h3 id="CRC8"><a href="#CRC8" class="headerlink" title="CRC8"></a>CRC8</h3><p>根据一个字节数据的CRC校验实现思想，两个字节或多个字节的数据也是同样的道理，加一层循环就可以了，代码实现如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">define</span> CRC8_POLYNOMIAL 0x31</span>

uint8_t <span class="token function">CheckCrc8</span><span class="token punctuation">(</span>uint8_t<span class="token operator">*</span> <span class="token keyword">const</span> message<span class="token punctuation">,</span> uint8_t initial_value<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    uint8_t  remainder<span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">//余数</span>
    uint8_t  i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">//循环变量</span>

    <span class="token comment" spellcheck="true">/* 初始化 */</span>
    remainder <span class="token operator">=</span> initial_value<span class="token punctuation">;</span>

    <span class="token keyword">for</span><span class="token punctuation">(</span>j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> <span class="token number">2</span><span class="token punctuation">;</span>j<span class="token operator">++</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        remainder <span class="token operator">^</span><span class="token operator">=</span> message<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>

        <span class="token comment" spellcheck="true">/* 从最高位开始依次计算  */</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">8</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>remainder <span class="token operator">&amp;</span> <span class="token number">0x80</span><span class="token punctuation">)</span>
            <span class="token punctuation">{</span>
                remainder <span class="token operator">=</span> <span class="token punctuation">(</span>remainder <span class="token operator">&lt;&lt;</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token operator">^</span>CRC8_POLYNOMIAL<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">else</span>
            <span class="token punctuation">{</span>
                remainder <span class="token operator">=</span> <span class="token punctuation">(</span>remainder <span class="token operator">&lt;&lt;</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/* 返回计算的CRC码 */</span>
    <span class="token keyword">return</span> remainder<span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>接下来用最开始在背景中提出的问题进行检，SHT30传感器的数据手册中给出了它计算CRC的生成多项式和初始值，并给出了一个示例，如图：</p>
<p><img src="http://mculover666.cn/image/20190809/wtLIFxbSLyon.png?imageslim" alt="mark"></p>
<p>接下来我们使用示例测试一下：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">char</span> dat<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">0xBE</span><span class="token punctuation">,</span><span class="token number">0xEF</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    uint8_t crc <span class="token operator">=</span> <span class="token function">CheckCrc8</span><span class="token punctuation">(</span>dat<span class="token punctuation">,</span> <span class="token number">0xFF</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"crc = %#x\n"</span><span class="token punctuation">,</span> crc<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>crc <span class="token operator">==</span> <span class="token number">0x92</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"ok.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">else</span>
    <span class="token punctuation">{</span>
      <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"fail.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>测试结果如下：</p>
<p><img src="http://mculover666.cn/image/20190809/VXPkJUIakUWH.png?imageslim" alt="mark"></p>
<h2 id="算法2-——-查表思想"><a href="#算法2-——-查表思想" class="headerlink" title="算法2 —— 查表思想"></a>算法2 —— 查表思想</h2><h3 id="生成表"><a href="#生成表" class="headerlink" title="生成表"></a>生成表</h3><p>首先需要编写一个程序，计算好所有的8位二进制数的CRC校验码，然后将它保存成一个256B大小的数组。</p>
<p>生成数组的代码如下：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    uint16_t i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    uint8_t crc <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token keyword">for</span><span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">256</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        crc <span class="token operator">=</span> <span class="token function">CheckCrc4</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"0x%02x, "</span><span class="token punctuation">,</span> crc<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token punctuation">(</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token operator">%</span><span class="token number">16</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
        <span class="token punctuation">{</span>
            <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<p>生成的表如图：</p>
<p><img src="http://mculover666.cn/image/20190809/ueP7lMrR9bjw.png?imageslim" alt="mark"></p>
<h3 id="查找表"><a href="#查找表" class="headerlink" title="查找表"></a>查找表</h3><p>将这张表保存为一个数组，然后编写新的校验CRC的程序：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">include</span> <span class="token string">&lt;stdint.h></span></span>

uint8_t CRC4_TABLE<span class="token punctuation">[</span><span class="token number">256</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">//……这里数据太多，省略</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token keyword">void</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    uint8_t dat <span class="token operator">=</span> <span class="token number">0xB3</span><span class="token punctuation">;</span>
    uint8_t crc <span class="token operator">=</span> CRC4_TABLE<span class="token punctuation">[</span>dat<span class="token punctuation">]</span><span class="token punctuation">;</span>      <span class="token comment" spellcheck="true">//直接查表</span>

    <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"crc = %#x\n"</span><span class="token punctuation">,</span> crc<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>crc <span class="token operator">==</span> <span class="token number">0x04</span><span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"ok.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">else</span>
    <span class="token punctuation">{</span>
      <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"fail.\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> 
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span></code></pre>
<h2 id="两种C语言实现方法比较"><a href="#两种C语言实现方法比较" class="headerlink" title="两种C语言实现方法比较"></a>两种C语言实现方法比较</h2><table>
<thead>
<tr>
<th align="center">实现思想</th>
<th align="center">优点</th>
<th align="center">缺点</th>
</tr>
</thead>
<tbody><tr>
<td align="center">按位计算</td>
<td align="center">占用内存空间极小</td>
<td align="center">计算速度慢，数据长度大时计算速度会非常慢</td>
</tr>
<tr>
<td align="center">查找表</td>
<td align="center">计算速度非常快</td>
<td align="center">占用内存空间大，数据长度大时表会占用非常大的空间</td>
</tr>
</tbody></table>
<h2 id="移植第三方库-——-LibCRC"><a href="#移植第三方库-——-LibCRC" class="headerlink" title="移植第三方库 —— LibCRC"></a>移植第三方库 —— LibCRC</h2><p>CRC的计算确实是一个非常头疼的事情，所以国外有大神开源了一个库专门用于CRC计算 —— LibCRC。</p>
<p>Libcrc是一个C语言实现的多平台MIT许可CRC库，其官网链接为：<a href="https://www.libcrc.org/" target="_blank" rel="noopener">www.libcrc.org</a>，其Github仓库为：<a href="https://github.com/lammertb/libcrc.git" target="_blank" rel="noopener">LibCRC</a>。</p>
<p>有兴趣的读者可以移植分享一下~</p>
<h2 id="使用硬件CRC校验电路"><a href="#使用硬件CRC校验电路" class="headerlink" title="使用硬件CRC校验电路"></a>使用硬件CRC校验电路</h2><p>在STM32L4上有一个专门的CRC校验外设，可以直接使用STM32CubeMX激活CRC校验，然后使用HAL调用进行校验，后续在<code>使用硬件IIC和硬件CRC驱动SHT30</code>这篇文章中会有介绍，敬请期待~</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.mculover666.cn" rel="external nofollow noreferrer">Mculover666</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.mculover666.cn/posts/1935373145/">http://www.mculover666.cn/posts/1935373145/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="http://www.mculover666.cn" target="_blank">Mculover666</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/CRC%E6%A0%A1%E9%AA%8C%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">CRC校验算法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,douban" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/we-chat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    

    

    

    
    <div class="livere-card card" data-aos="fade-up">
    <!-- 来必力City版安装代码 -->
    <div id="lv-container" class="card-content" data-id="city" data-uid="MTAyMC80Njg0OS8yMzM1MA">
        <script type="text/javascript">
            (function (d, s) {
                let j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') {
                    return;
                }

                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript。</noscript>
    </div>
    <!-- City版安装代码已完成 -->
</div>
    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/4251315252/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/3.jpg" class="responsive-img" alt="STM32CubeMX_17 | 使用硬件SPI驱动TFT-LCD（ST7789）">
                        
                        <span class="card-title">STM32CubeMX_17 | 使用硬件SPI驱动TFT-LCD（ST7789）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本篇详细的记录了如何使用STM32CubeMX配置STM32L431RCT6的硬件SPI外设与ST7789通信，驱动16bit TFT-LCD 屏幕。


0. 前言我的一些个人观点：

学习 SPI 外设驱动LCD屏幕没有必要手写驱动，学
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-08-07
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/STM32CubeMX/" class="post-category">
                                    STM32CubeMX
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/STM32CubeMX-TFT-LCD-SPI%E6%80%BB%E7%BA%BF/">
                        <span class="chip bg-color">STM32CubeMX TFT-LCD SPI总线</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/842429667/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="STM32CubeMX_16 | 使用硬件CRC校验数据（以SHT30为例）">
                        
                        <span class="card-title">STM32CubeMX_16 | 使用硬件CRC校验数据（以SHT30为例）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本篇详细的记录了如何使用STM32CubeMX配置STM32L431RCT6的硬件CRC外设校验数据，并用SHT30温湿度传感器为例检查是否可以正确校验。


1. 准备工作硬件准备
开发板首先需要准备一个开发板，这里我准备的是STM32L
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-08-06
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/STM32CubeMX/" class="post-category">
                                    STM32CubeMX
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/STM32CubeMX-%E6%B8%A9%E6%B9%BF%E5%BA%A6%E4%BC%A0%E6%84%9F%E5%99%A8-SHT30-CRC%E6%A0%A1%E9%AA%8C/">
                        <span class="chip bg-color">STM32CubeMX 温湿度传感器 SHT30 CRC校验</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2016</span>
            <a href="http://www.mculover666.cn" target="_blank">Mculover666</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">70.7k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2016";
                    var startMonth = "08";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">陇ICP备19002222号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Mculover666" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:mculover666@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2412828003" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2412828003" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/wang-shi-wei-67-38/activities" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/wang-shi-wei-67-38/activities" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?6e1efa0988723a1db6356535db2ae6bd";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
